<template>
  <AdminLayout>
    <el-card class="edit-exam-card">
      <template #header>
        <div class="card-header">
          <span>编辑考试</span>
        </div>
      </template>
      <el-form :model="examForm" :rules="rules" ref="examFormRef" label-width="120px">
        <el-form-item label="考试名称" prop="examName">
  <el-input v-model="examForm.examName" placeholder="请输入考试名称" />
</el-form-item>
<el-form-item label="所属课程" prop="courseId">
  <el-select v-model="examForm.courseId" placeholder="请选择所属课程" style="width: 100%">
    <el-option
      v-for="course in courseList"
      :key="course.courseId"
      :label="course.courseName"
      :value="course.courseId"
    />
  </el-select>
</el-form-item>
<el-form-item label="考试时长" prop="examDuration">
  <el-input-number v-model="examForm.examDuration" :min="5" :max="300" style="width: 100%" />
  <div class="form-hint">单位：分钟（可为空表示不限制）</div>
</el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="examForm.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="examForm.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="examForm.totalScore" :min="10" :max="500" style="width: 100%" />
        </el-form-item>
        <el-form-item label="考试说明" prop="description">
          <el-input v-model="examForm.description" type="textarea" :rows="4" placeholder="请输入考试说明" />
        </el-form-item>
        
        <!-- 题目选择部分 -->
        <el-form-item label="题目列表">
          <div class="questions-section">
            <div class="questions-header">
              <el-button type="primary" @click="openQuestionSelector" size="small">
                <el-icon><Plus /></el-icon> 添加题目
              </el-button>
              <div class="total-score">总分：{{ totalQuestionsScore }} 分</div>
            </div>
            
            <el-table :data="examForm.questionList" style="width: 100%" max-height="400">
              <el-table-column type="index" label="#" width="50"></el-table-column>
              <el-table-column prop="questionContent" label="题目内容" min-width="200">
                <template #default="{ row }">
                  <div class="question-content">{{ row.questionContent }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="typeId" label="题型" width="80">
                <template #default="{ row }">
                  <el-tag v-if="row.typeId === 1">单选题</el-tag>
                  <el-tag v-else-if="row.typeId === 2">多选题</el-tag>
                  <el-tag v-else-if="row.typeId === 3">判断题</el-tag>
                  <el-tag v-else>其他</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="分值" width="120">
                <template #default="{ row, $index }">
                  <el-input-number 
                    v-model="row.score" 
                    :min="0.5" 
                    :max="100" 
                    :step="0.5" 
                    size="small"
                    @change="handleScoreChange"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row, $index }">
                  <el-button type="danger" size="small" @click="removeQuestion($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存修改</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 题目选择弹窗 -->
    <el-dialog
      v-model="questionSelectorVisible"
      title="选择题目"
      width="80%"
      top="5vh"
      :before-close="handleCloseQuestionSelector"
    >
      <div class="question-selector">
        <el-table 
          :data="questionList" 
          style="width: 100%" 
          max-height="400"
          @selection-change="handleSelectionChange"
          ref="questionTableRef"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="questionId" label="题目ID" width="80"></el-table-column>
          <el-table-column prop="course" label="所属课程" width="120"></el-table-column>
          <el-table-column prop="type" label="题型" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.typeId === 1">单选题</el-tag>
              <el-tag v-else-if="row.typeId === 2">多选题</el-tag>
              <el-tag v-else-if="row.typeId === 3">判断题</el-tag>
              <el-tag v-else>其他</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="questionContent" label="题目内容" min-width="200">
            <template #default="{ row }">
              <div class="question-content">{{ row.questionContent }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="80">
            <template #default="{ row }">
              <el-tag v-if="row.difficulty === '简单'" type="success">简单</el-tag>
              <el-tag v-else-if="row.difficulty === '中等'" type="warning">中等</el-tag>
              <el-tag v-else-if="row.difficulty === '困难'" type="danger">困难</el-tag>
              <span v-else>{{ row.difficulty }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="默认分值" width="100">
            <template #default="{ row }">
              {{ row.score }} 分
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination">
          <el-pagination
            v-model:current-page="questionPage.currentPage"
            v-model:page-size="questionPage.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="questionPage.total"
            @size-change="handleQuestionSizeChange"
            @current-change="handleQuestionCurrentChange"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseQuestionSelector">取消</el-button>
          <el-button type="primary" @click="addSelectedQuestions">添加选中题目</el-button>
        </span>
      </template>
    </el-dialog>
    </AdminLayout>
  </template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { get, postJson } from '../../utils/api'
import AdminLayout from '../../components/admin/AdminLayout.vue'

// 定义题目类型
interface Question {
  questionId: number
  courseId?: number
  typeId: number
  course?: string
  type?: string
  questionContent: string
  optionA?: string | null
  optionB?: string | null
  optionC?: string | null
  optionD?: string | null
  correctAnswer: string
  score: number
  difficulty: string
}

// 定义考试表单类型
interface ExamForm {
  examId?: number
  examName: string
  startTime: string
  endTime: string
  totalScore: number
  examDuration: number | null
  description: string
  courseId: number | undefined
  questionList: Question[]
}

const router = useRouter()
const route = useRoute()
const examFormRef = ref()

// 考试表单数据
const examForm = reactive<ExamForm>({
  examId: undefined,
  examName: '',
  startTime: '',
  endTime: '',
  totalScore: 100,
  examDuration: null,
  description: '',
  courseId: undefined,
  questionList: []
})

// 教师ID和课程列表
const teacherId = ref<number | null>(null)
const courseList = ref<any[]>([])

// 表单验证规则
const rules = {
  examName: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    { min: 2, max: 100, message: '考试名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  totalScore: [
    { required: true, message: '请输入总分', trigger: 'blur' }
  ]
}

// 题目选择器相关
const questionSelectorVisible = ref(false)
const questionList = ref<Question[]>([])
const selectedQuestions = ref<Question[]>([])
const questionTableRef = ref()

// 题目分页
const questionPage = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算题目总分
const totalQuestionsScore = computed(() => {
  return examForm.questionList.reduce((total, question) => total + (question.score || 0), 0)
})

// 获取教师ID
const fetchTeacherId = async () => {
  try {
    const response = await get('/teacher/get/my')
    if (response.code === 200 && response.data) {
      teacherId.value = response.data
    } else {
      ElMessage.error(response.msg || '获取教师ID失败')
    }
  } catch (error) {
    console.error('获取教师ID失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 获取课程列表
const fetchCourseList = async () => {
  try {
    const response = await get('/course/query/all')
    if (response.code === 200 && response.data) {
      courseList.value = response.data
    } else {
      ElMessage.error(response.msg || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 获取题目列表
const fetchQuestions = async () => {
  try {
    const response = await get('/question-bank/query', {
      page: questionPage.currentPage,
      size: questionPage.pageSize
    })
    
    if (response.code === 200) {
      questionList.value = response.data || []
      questionPage.total = response.dataCount || response.data.length
    } else {
      ElMessage.error(response.msg || '获取题目列表失败')
    }
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 打开题目选择器
const openQuestionSelector = () => {
  questionSelectorVisible.value = true
  // 获取题目列表
  fetchQuestions().then(() => {
    // 在题目列表获取完成后，预选中已有的题目
    nextTick(() => {
      if (questionTableRef.value && examForm.questionList.length > 0) {
        // 获取当前已选中的题目ID列表
        const selectedQuestionIds = new Set(examForm.questionList.map(q => q.questionId))
        
        // 遍历题目列表，预选中已有的题目
        questionList.value.forEach((question) => {
          if (selectedQuestionIds.has(question.questionId)) {
            questionTableRef.value.toggleRowSelection(question, true)
          }
        })
      }
    })
  })
}

// 关闭题目选择器
const handleCloseQuestionSelector = () => {
  questionSelectorVisible.value = false
  selectedQuestions.value = []
}

// 处理题目选择变化
const handleSelectionChange = (selection: Question[]) => {
  selectedQuestions.value = selection
}

// 添加选中题目
const addSelectedQuestions = () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请至少选择一个题目')
    return
  }
  
  // 过滤掉已存在的题目（根据questionId去重）
  const existingQuestionIds = new Set(examForm.questionList.map(q => q.questionId))
  const newQuestions = selectedQuestions.value.filter(q => !existingQuestionIds.has(q.questionId))
  
  if (newQuestions.length === 0) {
    ElMessage.warning('选中的题目已存在')
    handleCloseQuestionSelector()
    return
  }
  
  // 添加到考试题目列表
  examForm.questionList.push(...newQuestions.map(q => ({
    ...q,
    score: q.score || 1 // 使用题目默认分值
  })))
  
  ElMessage.success(`成功添加 ${newQuestions.length} 道题目`)
  handleCloseQuestionSelector()
}

// 移除题目
const removeQuestion = (index: number) => {
  ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    examForm.questionList.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 处理题目分值变化
const handleScoreChange = () => {
  // 可以在这里添加一些验证逻辑
}

// 题目分页相关方法
const handleQuestionSizeChange = (size: number) => {
  questionPage.pageSize = size
  fetchQuestions()
}

const handleQuestionCurrentChange = (current: number) => {
  questionPage.currentPage = current
  fetchQuestions()
}

// 获取考试详情
const fetchExamDetail = async (examId: number) => {
  try {
    // 调用获取考试详情的接口
    const response = await get(`/exam/query/id?id=${examId}`)
    
    if (response.code === 200 && response.data) {
      const examData = response.data
      examForm.examId = examData.examId
      examForm.examName = examData.examName
      examForm.startTime = examData.startTime
      examForm.endTime = examData.endTime
      examForm.totalScore = examData.totalScore
      examForm.examDuration = examData.examDuration
      examForm.description = examData.description
      
      // 处理题目列表
      if (examData.questionList && Array.isArray(examData.questionList)) {
        examForm.questionList = examData.questionList.map((q: any) => ({
          questionId: q.questionId,
          typeId: q.typeId,
          questionContent: q.questionContent,
          optionA: q.optionA,
          optionB: q.optionB,
          optionC: q.optionC,
          optionD: q.optionD,
          correctAnswer: q.correctAnswer,
          score: q.score,
          difficulty: q.difficulty
        }))
      } else {
        examForm.questionList = []
      }
    } else {
      ElMessage.error(response.msg || '获取考试详情失败')
      router.push('/teacher/exam/list')
    }
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败')
    router.push('/teacher/exam/list')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await examFormRef.value.validate()
    
    // 检查时间逻辑
    if (new Date(examForm.startTime) >= new Date(examForm.endTime)) {
      ElMessage.error('开始时间必须小于结束时间')
      return
    }
    
    // 检查是否有题目
    if (examForm.questionList.length === 0) {
      ElMessage.error('请至少添加一道题目')
      return
    }
    
    // 检查是否选择了课程
    if (!examForm.courseId) {
      ElMessage.error('请选择所属课程')
      return
    }
    
    // 检查题目分值
    const hasZeroScore = examForm.questionList.some(q => !q.score || q.score <= 0)
    if (hasZeroScore) {
      ElMessage.error('请确保所有题目的分值都大于0')
      return
    }
    
    // 准备提交数据
    const submitData = {
      examId: examForm.examId,
      examName: examForm.examName,
      startTime: examForm.startTime,
      endTime: examForm.endTime,
      totalScore: examForm.totalScore,
      examDuration: examForm.examDuration,
      description: examForm.description,
      teacherId: teacherId.value,
      courseId: examForm.courseId,
      questionList: examForm.questionList.map(q => ({
        score: q.score,
        typeId: q.typeId,
        questionId: q.questionId
      }))
    }
    
    // 发送请求
    const response = await postJson('/exam/updata/teacher', submitData)
    
    if (response.code === 200) {
      ElMessage.success('考试修改成功')
      // 跳转回考试列表页面
      router.push('/teacher/exam/list')
    } else {
      ElMessage.error(response.msg || '考试修改失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/teacher/exam/list')
}

// 页面加载时获取数据
onMounted(async () => {
  // 获取教师ID和课程列表
  await fetchTeacherId()
  await fetchCourseList()
  
  // 获取考试ID
  const examId = Number(route.params.id)
  if (!examId || isNaN(examId)) {
    ElMessage.error('无效的考试ID')
    router.push('/teacher/exam/list')
    return
  }
  
  // 获取考试详情
  await fetchExamDetail(examId)
})
</script>

<style scoped>
.edit-exam-card {
  width: 100%;
  max-width: 1000px;
  margin: 20px auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.form-hint {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.questions-section {
  width: 100%;
}

.questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.total-score {
  font-weight: bold;
  color: #409eff;
}

.question-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .edit-exam-card {
    margin: 10px;
  }
  
  .questions-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
